package com.emily.test.controller;


import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.TMenu;
import com.emily.test.service.RedisService;
import com.emily.test.service.TMenuService;
import com.emily.test.service.TResourceService;
import com.emily.test.service.TRoleMenuService;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.annotations.Api;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "tMenuController")
@Api(value = "TMenuApi", description = "TMenu接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class TMenuController {

    private Logger logger = LoggerFactory.getLogger(TMenuController.class);

    @Autowired
    private TResourceService tResourceService;
    @Autowired
    private RedisService redisService;

    @Autowired
    private TMenuService tMenuService;

    @Autowired
    private TRoleMenuService tRoleMenuService;


    /**
     * 根据条件查询所有菜单列表
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据条件查询所有菜单列表", notes="根据条件查询所有菜单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单ID"),
            @ApiImplicitParam(name = "menuName", value = "菜单名称"),
            @ApiImplicitParam(name = "resourceId", value = "资源ID"),
            @ApiImplicitParam(name = "pageurl", value = "菜单URL"),
            @ApiImplicitParam(name = "state", value = "启用状态：1、启用；0、禁用；2、删除状态"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间")
    })
    @PostMapping(value = "getAllMenuInfoList")
    public ResponseResult getAllMenuInfoList(@RequestBody(required = false) JSONObject jsonObject){
        TMenu tMenu=new TMenu();
        if(!ConstentUtil.isEmpty(jsonObject)){
            Integer id=jsonObject.getInteger("id") == null ? null : (Integer) jsonObject.getInteger("id");
            String menuName=jsonObject.getString("menuName");
            Integer pid=jsonObject.getInteger("pid");
            String pageurl=jsonObject.getString("pageurl");
            String updateTime=jsonObject.getString("updateTime");
            String resourceName=jsonObject.getString("resourceName");
            Integer resourceId =jsonObject.getInteger("resourceId") == null ? null : jsonObject.getInteger("resourceId");
            Integer state =jsonObject.getInteger("state") == null ? null : jsonObject.getInteger("state");
            tMenu.setId(id);
            tMenu.setMenuName(menuName);
            tMenu.setPageurl(pageurl);


            Integer resId=null;
            if(!ConstentUtil.isEmpty(pid)){
                resId=pid;
            }else{
                resId=resourceId;
            }
            tMenu.setResourceId(resId);
            tMenu.setResourceName(resourceName);
            tMenu.setState(state);
            tMenu.setUpdateTime(updateTime);
        }
        try {
            List<TMenu> menuList=tMenuService.getMenuInfoListByCondition(tMenu);
            logger.info("根据条件查询菜单列表成功:{}",menuList);
            return ResponseResult.success(menuList);
        } catch (Exception e) {
            logger.info("根据条件查询菜单列表异常:",e);
            e.printStackTrace();
            return ResponseResult.fail("根据条件查询失败");
        }
    }

    /**
     * 根据条件查询菜单列表
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据条件查询菜单列表", notes="根据条件查询菜单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单ID"),
            @ApiImplicitParam(name = "menuName", value = "菜单名称"),
            @ApiImplicitParam(name = "resourceId", value = "资源ID"),
            @ApiImplicitParam(name = "pageurl", value = "菜单URL"),
            @ApiImplicitParam(name = "state", value = "启用状态：1、启用；0、禁用；2、删除状态"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间")
    })
    @PostMapping(value = "getMenuInfoList")
    public ResponseResult getMenuInfoList(@RequestBody(required = false) JSONObject jsonObject, HttpServletRequest request){
        TMenu tMenu=new TMenu();
        List<TMenu> menuLs=new ArrayList<TMenu>();
        if(!ConstentUtil.isEmpty(jsonObject)){
            Integer id=jsonObject.getInteger("id") == null ? null : (Integer) jsonObject.getInteger("id");
            String menuName=jsonObject.getString("menuName");
            Integer pid=jsonObject.getInteger("pid");
            String pageurl=jsonObject.getString("pageurl");
            String updateTime=jsonObject.getString("updateTime");
            String resourceName=jsonObject.getString("resourceName");
            Integer resourceId =jsonObject.getInteger("resourceId") == null ? null : jsonObject.getInteger("resourceId");
            Integer state =jsonObject.getInteger("state") == null ? null : jsonObject.getInteger("state");
            tMenu.setId(id);
            tMenu.setMenuName(menuName);
            tMenu.setPageurl(pageurl);


            Integer resId=null;
            if(!ConstentUtil.isEmpty(pid)){
                resId=pid;
            }else{
                resId=resourceId;
            }
            tMenu.setResourceId(resId);
            tMenu.setResourceName(resourceName);
            tMenu.setState(state);
            tMenu.setUpdateTime(updateTime);
        }
        String token = request.getHeader("token");
        Map<String,Object> userMap=  (Map<String,Object>)redisService.get(token);
        List<Map<String, Object>> roleList = (List<Map<String, Object>>) userMap.get("userRoleList");
        List<Integer> roleIds=new ArrayList<Integer>();
        if(!ConstentUtil.isEmpty(roleList)){
            for(Map<String, Object> mp : roleList){
                   Integer roleId= (Integer) mp.get("roleId");
                   roleIds.add(roleId);
            }
        }
        List<Map<String, Object>> menuLists= tRoleMenuService.getMenuListByRoleIds(roleIds);
        try {
            List<TMenu> menuList=tMenuService.getMenuInfoListByCondition(tMenu);

            if(!ConstentUtil.isEmpty(menuLists)){
                for(Map<String, Object> men : menuLists){
                      Integer menuIds= (Integer) men.get("id");
                      if(!ConstentUtil.isEmpty(menuList)){
                          for(TMenu m : menuList){
                                Integer mId=m.getId();
                                if(menuIds.equals(mId)){
                                    menuLs.add(m);
                                }
                          }
                      }
                }
            }

            logger.info("根据条件查询菜单列表成功:{}",menuLs);
            return ResponseResult.success(menuLs);
        } catch (Exception e) {
            logger.info("根据条件查询菜单列表异常:",e);
            e.printStackTrace();
            return ResponseResult.fail("根据条件查询失败");
        }
    }
    /**
     * 增加一条菜单信息,默认为启用
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="增加一条菜单信息", notes="增加一条菜单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单ID"),
            @ApiImplicitParam(name = "menuName", value = "菜单名称",required = true),
            @ApiImplicitParam(name = "resourceId", value = "资源ID",required = true),
            @ApiImplicitParam(name = "resourceName", value = "资源名称",required = true),
            @ApiImplicitParam(name = "pageurl", value = "菜单URL"),
            @ApiImplicitParam(name = "state", value = "启用状态：1、启用；0、禁用；2、删除状态"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间")
    })
    @PostMapping(value = "insertMenuInfo")
    public ResponseResult insertMenuInfo(@RequestBody JSONObject jsonObject) throws Exception {
        TMenu tMenu= (TMenu) ConstentUtil.json2Object(jsonObject,TMenu.class);
        if(!ConstentUtil.isEmpty(tMenu.getState())){
            tMenu.setState(1);
        }
        tMenu.setUpdateTime(DateUtil.getNowStr());
        try {
            int num= tMenuService.insertMenuInfo(tMenu);
            logger.info("添加菜单信息成功:{}",num);
            return ResponseResult.success(num);
        } catch (Exception e) {
            logger.error("添加菜单异常",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    /**
     * 修改一条菜单信息
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="修改一条菜单信息", notes="修改一条菜单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单ID",required = true),
            @ApiImplicitParam(name = "menuName", value = "菜单名称"),
            @ApiImplicitParam(name = "resourceId", value = "资源ID"),
            @ApiImplicitParam(name = "resourceName", value = "资源名称"),
            @ApiImplicitParam(name = "pageurl", value = "菜单URL"),
            @ApiImplicitParam(name = "state", value = "启用状态：1、启用；0、禁用；2、删除状态"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间")
    })
    @PostMapping(value = "modifyMenuInfoById")
    public ResponseResult modifyMenuInfoById(@RequestBody JSONObject jsonObject) throws Exception {
        TMenu tMenu= (TMenu) ConstentUtil.json2Object(jsonObject,TMenu.class);
        if(ConstentUtil.isEmpty(tMenu.getId())){
            return ResponseResult.fail("菜单id"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        tMenu.setUpdateTime(DateUtil.getNowStr());
        try {
            int num= tMenuService.modifyMenuInfoById(tMenu);
            return ResponseResult.success(num);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 禁用多个菜单
     * @param jsonObject    其中菜单ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="禁用多个菜单", notes="根据id禁用菜单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "菜单ID列表", required = true)
    })
    @PostMapping(value = "disabledMenusById")
    public ResponseResult disabledMenusById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TMenu> tMenuList=new ArrayList<TMenu>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                TMenu tMenu=new TMenu();
                tMenu.setId(ConstentUtil.strToInteger(idStr[i]));
                tMenu.setState(0);
                tMenuList.add(tMenu);
            }
        }
        try {
            int num=tMenuService.updateMenuInfoByCondition(tMenuList);
            logger.info("ids为{}的菜单已禁用",ids);
            return ResponseResult.success("0","禁用成功",tMenuList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("禁用失败");
        }
    }

    /**
     * 启用多个菜单
     * @param jsonObject    其中菜单ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="启用多个菜单信息", notes="根据id启用菜单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "菜单ID列表", required = true)
    })
    @PostMapping(value = "enabledMenusById")
    public ResponseResult enabledMenusById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TMenu> tMenuList=new ArrayList<TMenu>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                TMenu tMenu=new TMenu();
                tMenu.setId(ConstentUtil.strToInteger(idStr[i]));
                tMenu.setState(1);
                tMenuList.add(tMenu);
            }
        }
        try {
            int num=tMenuService.updateMenuInfoByCondition(tMenuList);
            logger.info("ids为{}的菜单已启用",ids);
            return ResponseResult.success("0","启用成功",tMenuList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("启用成功");
        }
    }
    /**
     * 删除菜单（假删除，令state=2）
     * @param jsonObject    其中菜单ids的格式为:{1,2,3,4}
     * @return
     */
    @ApiOperation(value="删除多个菜单信息", notes="根据id删除菜单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "菜单ID列表", required = true)
    })
    @PostMapping(value = "deleteMenusById")
    public ResponseResult deleteMenusById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TMenu> tMenuList=new ArrayList<TMenu>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                TMenu tMenu=new TMenu();
                tMenu.setId(ConstentUtil.strToInteger(idStr[i]));
                tMenu.setState(2);
                tMenuList.add(tMenu);
            }
        }
        try {
            int num=tMenuService.updateMenuInfoByCondition(tMenuList);
            logger.info("ids为{}的菜单已删除",ids);
            return ResponseResult.success("0","删除成功",tMenuList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除成功");
        }
    }

//    public ResponseResult getMenuInfoAndResourceAllByMenuId(@RequestBody JSONObject jsonObject){
//        try {
//
//        }
//        return ResponseResult.success();
//    }
}
